import os
import shutil

from constants import consts
from logger import logger
from sub_events.base_event import BaseEvent

LOGGER = logger.CustomLogger()

class UpdateOwnerCfgEvent(BaseEvent):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.event_name_zh: str = "更新owner_config文件"
        self.event_name_en: str = "Update owner_config.json"

    def pre_execute(self) -> bool:
        return self.check_owner_config_updated(self.hook.pr_number)

    def execute(self) :
        # 请求下载文件到本地
        LOGGER.info(f"[{self.hook.pr_number}] update owner_config.json file")
        self.OCM.backup_owner_config()
        owner_config_url = self.cfg.get("repo", {}).get("owner_config_url")
        file_path = 'config/' + self.hook.user_agent.replace("-", "_") + '/owner_config.json'
        os.system(f'wget -O owner_config.json {owner_config_url}')
        shutil.copy2("owner_config.json", file_path)
        self.OCM.load_owner_config()
        return False

    def check_owner_config_updated(self, pr_number):
        try:
            params = {'access_token': self.get_admin_token()}
            files = self.git_client.get_filenames(pr_number, params=params)
            for filename in files:
                if consts.OWNER_CONFIG_FILENAME in filename:
                    return True
            return False
        except Exception as e:
            LOGGER.error(f"[{self.hook.pr_number}] get files failed, details: {str(e)}")
            return False
